<?php

/*
 * This will be the Edit Security Group page. 
 * 
 * Created by: Peter Agno Jr.
 * Date created: December 5, 2011
 */

    include("siteTop.php"); 
    include('includes/siteConfig.php'); 

    // connect to database
    $connect = mysql_connect($hostName,$rootName,$dBasePassword) or die ('Unable to connect!');
    mysql_select_db($dBaseName) or die ('Unable to select database!');
    
    // Get the data from post
    $securityGroupId = $_POST['securityGroupId'];
    
    // Get deptPosId details
    $query =
        "
            SELECT *
            FROM SecurityGroup
            WHERE securityGroupId = '$securityGroupId'
        ";

    $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
    $row = mysql_fetch_array($result);
    $securityGroupId = $row['securityGroupId'];
    $securityGroupName = $row['securityGroupName'];
?>

<!-- HEADER START -->
    <!--JAVASCRIPT SOURCES-->
    <script src="js/jquery-1.6.2.min.js"></script>
    
    <!--ACTUAL JS SCRIPTS AND JQUERIES-->
    <script type="text/javascript">
        jQuery(document).ready(function(){ 
            var rowPerm = 0; // variable for the number of total permissions of the security group
            
            // CHANGE FIRST THE CSS OF THE NAV BAR
            jQuery("#adminTools-nav").addClass("highlightMenuBar");
            jQuery("#secGrpSetup-nav").addClass("highlightMenuBar");
            
            addPermRows();
            
            // Start - Add another row in Security Group's Permission Screenlet
            jQuery('#addPermBtn').live("click",function() {
                addSecGrpPermRow();
            }); // End - Add another row in Security Group's Permission Screenlet
            
            // Start - Remove a permission row
            jQuery('.removePermBtn').live("click",function() {
                buttonId = this.id;
                tempSubstr = buttonId.split('_');
                jQuery("#rowPermId_"+tempSubstr[1]).remove();
                
                // Add a permission row if the table row is equal to 1 (header's row)
                if ( jQuery('#secGrpPermTable tr').length == 2 ) {
                    jQuery("#addPermBtn").click();
                }
            }); // End - Remove a permission row
            
            // Start - edit security group
            jQuery('#editSecGrpButton').live("click",function() {
                if ( jQuery("#securityGroupName").val() == "" ) {
                    // Show error message if the user clicked the edit button
                    // but haven't inputted all of the neccessary information.
                    alert("Please input the required information.");
                }
                else if ( noSamePerm() != true ) {
                    alert("Error : There should be no same permission.");
                }
                else {
                    var permIds = "";
                    // Get each of the value of permId
                    jQuery('.permId').each(function(index) {
                        permIds += jQuery('#' + this.id).val() + ",";
                    });
                    
                    // Start - Ajax the editing of security group
                    jQuery.ajax({
                        type : 'POST',
                        url : 'ajaxRequests/admSecGroupEdit.php',
                        dataType : 'json',
                        async : false,
                        data: {
                            securityGroupId : jQuery("#securityGroupId").val(),
                            securityGroupName : jQuery("#securityGroupName").val(),
                            permIds : permIds
                        },
                        success : function(data){
                            // If, successful editing of security group
                            if (data) {
                                if ( data[0].flag == "success" ) {
                                    jQuery("#secGrpSuccessMessage").val(data[0].msg);
                                    jQuery("#secGrpStpMsgForm").submit();
                                }
                                else {
                                    alert(data[0].msg);
                                }
                            } // End if, successful editing of security group
                        },
                        error : function() {
                            alert("Error : Editing the security group was not successful.");
                        }
                    }); // End - Ajax the editing of security group
                } // End else
            }); // End - edit security group
            
            // Start - Go back to admSecGroupSetup.php
            jQuery('#admSecGrpStpBtn').live("click",function() {
                window.location = 'admSecGroupSetup.php';
            }); // End - Go back to admSecGroupSetup.php
            
            // Start - Function: Check if there is same permission in Security Group's Permission Screenlet
            function noSamePerm() {
                noSame = true;
                
                if ( jQuery('#posPermTable tr').length == 3 ) {
                    return noSame;
                }
                else {
                    for( x = 1 ; x <= rowPerm && noSame == true ; x++ ){
                        for( y = 1 ; y <= rowPerm && noSame == true ; y++ ){
                            if ( x != y ) {
                                if ( jQuery("#permId_"+x).val() == jQuery("#permId_"+y).val() && jQuery("#permId_"+x).val() != undefined && jQuery("#permId_"+y).val() != undefined  ) {
                                    noSame = false;
                                }
                            }
                        }
                    }
                    
                    return noSame;
                }
            } // End - Function: Check if there is same permission in Security Group's Permission Screenlet
            
            // Start - Add n number of rows of addSecGrpPermRow()
            function addPermRows() {
                var x = 0;
                x = parseInt(x);
                y = parseInt(jQuery("#permNumRows").val());
                
                for ( ; x < y ; x++ ) {
                    addSecGrpPermRow();
                }
                
                adjustPerm(y);
            } // End - Add n number of rows of addSecGrpPermRow()
            
            // Start - Function: Add another row in Security Group's Permission Screenlet
            function addSecGrpPermRow() {
                jQuery.ajax({
                    type : 'POST',
                    url : 'ajaxRequests/admGetPermissionList.php',
                    dataType : 'json',
                    async : false,
                    data: {
                    },
                    success : function(data){
                        if (data) {
                            permRow = "";
                            rowPerm++;
                            permRow += "<tr id='rowPermId_"+rowPerm+"'>";

                            // Prepare the Security Group dropdown
                            permRow += "<td><select name='permId' id='permId_"+rowPerm+"' class='permId'>";
                                
                            jQuery.each(data, function(index, data) {
                                permRow += "<option value='"+data.permissionId+"'>"+data.permissionName+"</option>";
                            });
                            
                            permRow += "</select></td>";    // Close the Permission dropdown
                                
                            // Prepare the Remove button
                            permRow += "<td style='text-align:center;'><img src='images/ximage.png' height='20px' width='20px' style='cursor: pointer;' name='removePermBtn' id='removePermBtn_"+rowPerm+"' class='removePermBtn'/></td>";
                            permRow += "</tr>"; // Close the row
                            jQuery(".permAddRow").before(permRow);    // Append the row
                        } 
                    },
                    error : function() {
                        alert("Error : Adding permission row was not successful.");
                    }
                });
            } // End - Function: Add another row in Security Group's Permission Screenlet
            
            // Start - Adjust the value of the dropdown of the permissions
            function adjustPerm(numPermRows) {
                var thePerms = jQuery("#thePerms").val();
                tempPerms = thePerms.split(',');
                
                for ( x = 0 ; x < numPermRows ; x++ ) {
                    jQuery("#permId_"+ (x+1)).val(tempPerms[x]);
                }
            } // End - Adjust the value of the dropdown of the permissions
            
        }); // End - jQuery document ready
    </script>
<!-- HEAD END -->

<div id="content">
<h1>Edit Security Group</h1>
    <div class="contentbox">       
        <?php
        // Check permission
        $thePermissions = array('SECGRPSTP');
        if ( checkPermission( $thePermissions, $userId ) == true ) {
        ?>
            <span class="screenlet" >Security Group Information</span>
            <table>
                <tr>
                    <td>Security Group ID : </td>
                    <td>
                        <input type="hidden" name="securityGroupId" id="securityGroupId" value="<?php echo $securityGroupId; ?>"/>
                        <?php echo $securityGroupId; ?>
                    </td>
                </tr>
                <tr>
                    <td>Security Group Name : </td>
                    <td>
                        <input type="text" name="securityGroupName" id="securityGroupName" value="<?php echo $securityGroupName; ?>"/>
                    </td>
                </tr>
            </table>
            
            <span class="screenlet" >Select Permissions</span>
            <table border="1" id="secGrpPermTable">
                <tr>
                    <th>Permission Name</th>
                    <th>Action</th>
                </tr>
                <tr class="permAddRow">
                    <th></th>
                    <th><input type="Submit" name="addPermBtn" id="addPermBtn" value="Add" class="siteGreenButton" /></th>
                </tr>
            </table>
            
            <?php
                // Add the number of Permission
                // Get the permission and its number
                $permQuery =
                    "
                        SELECT P.permissionId as permissionId, P.permissionName as permissionName
                        FROM SecurityGroup_Permission as SGP, Permission as P
                        WHERE SGP.securityGroupId = '$securityGroupId'
                            AND SGP.permissionId = P.permissionId
                        ORDER BY P.permissionName
                    ";

                $permResult = mysql_query($permQuery) or die ('Error in query: $permQuery. ' . mysql_error());
                $permNumRows = mysql_num_rows($permResult);
                
                $thePerms = "";
                while ( $permRow = mysql_fetch_array($permResult) ) {
                    $thePerms = $thePerms . $permRow['permissionId'] . ",";
                }
                mysql_free_result($permResult);
            ?>
            <input type="hidden" name="thePerms" id="thePerms" value="<?php echo $thePerms;?>" />
            <input type="hidden" name="permNumRows" id="permNumRows" value="<?php echo $permNumRows;?>" />
            
            <input type="Submit" name="editSecGrpButton" id="editSecGrpButton" value="Edit" class="siteGreenButton" />
            <input type="Submit" name="admSecGrpStpBtn" id="admSecGrpStpBtn" value="Cancel" class="siteRedButton" />
            
            <!-- Hidden form to be used when the editing of security group was successful -->
            <form id="secGrpStpMsgForm" name="secGrpStpMsgForm" action="admSecGroupSetup.php" method="POST">
                <input type="hidden" name="secGrpSuccessMessage" id="secGrpSuccessMessage" value=""/>
            </form>
        <?php
            mysql_free_result($result);
        }
        else {
            echo "<div class='noPermissionMsgBox noPermissionMsg' style='border: 2px solid red'><div id='noPermissionMsgs'>You have no permission to view this page.</div></div>";
        }
        // End checking permission
        ?>
    </div> <!-- contentbox end div -->
    <div style="position:relative; visibility: hidden">end</div>    <!-- extra space for contentbox -->
</div> <!-- content end div -->
<?php
    include ("siteBottom.php"); 
?>

